package my.edu.utils;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import my.edu.common.constant.MessageConstant;
import my.edu.common.domain.OrderProductDetail;
import my.edu.common.domain.purchase.PriceAndQuantity;
import my.edu.common.exception.BillsException;
import my.edu.common.exception.Order.PurchaseException;
import my.edu.common.exception.Order.SalesException;
import my.edu.common.myInterface.AccountCount;
import my.edu.common.myInterface.CanAudit;
import my.edu.constant.DeliveryMethod;
import my.edu.model.User.service.IUserService;
import my.edu.model.bills.purchase.entity.PurchaseOrder;
import my.edu.model.bills.sales.entity.SalesOrderDetail;
import my.edu.model.commodity.service.IProductService;
import my.edu.model.information.service.IAccountService;
import my.edu.model.information.service.ICustomerService;
import my.edu.model.information.service.ISupplierService;
import my.edu.security.userEntity.UserDetail;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.YearMonth;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class OrderServiceUtil {

    @Autowired
    private IProductService productService;
    @Autowired
    private IUserService userService;

    @Autowired
    private ICustomerService customerService;
    @Autowired
    private IAccountService accountService;
    @Autowired
    private ISupplierService supplierService;
    @Autowired
    private DeliveryMethod deliveryMethod;

    public PriceAndQuantity checkAndGetProductDetail(String status, List<? extends OrderProductDetail> list) {
        // 检查 productId 是否有重复
        Set<Long> productIds = new HashSet<>();
        for (OrderProductDetail orderProductDetail : list) {
            Long productId = orderProductDetail.getProductId();
            //商品id存在
            if (productId == null || productId <= 0) {
                throw new BillsException(MessageConstant.PRODUCT_IS_NULL);
            }
            //商品id不重复
            if (!productIds.add(productId)) {
                throw new BillsException(MessageConstant.PRODUCT_RESEE);
            }
        }
        return productService.chackAndGetTotal(list, status);
    }


    public <T extends CanAudit> void setAuditStatus(IService<T> service, List<Long> ids, boolean b) {
        Class<?> entityClass = service.getEntityClass();
        UpdateWrapper<T> updateWrapper = new UpdateWrapper<>();
        if (b) {
            UserDetail userDetail = (UserDetail) SecurityUtils.getSubject().getPrincipal();
            updateWrapper
                    .set("is_audited", 1)
                    .set("auditor_id", userDetail.getId())
                    .set("auditor_name", userDetail.getUsername())
                    .in("id", ids);
            service.update(updateWrapper);
        } else {
            updateWrapper
                    .set("is_audited", 0)
                    .set("auditor_id", null)
                    .set("auditor_name", null)
                    .in("id", ids);
            service.update(updateWrapper);
        }
    }

    public Map<Long, BigDecimal> getAccountIdToTotalAmountMap(List<? extends AccountCount> orders) {
        return orders.stream()
                .filter(order -> order.getSettlementAccountId() != null)
                .collect(Collectors.groupingBy(
                        AccountCount::getSettlementAccountId, // 按账户ID分组
                        Collectors.mapping(
                                AccountCount::getCirculatingMoney,      // 提取支付金额
                                Collectors.reducing(BigDecimal.ZERO, BigDecimal::add) // 聚合求和
                        )
                ));
    }

    public void checkDTO(String method, Long settlementAccountId, Long salespersonId, Long supplierId, Long customerId) {
        //检查交货方式
        if (method != null) deliveryMethod.checkDeliveryMethod(method);
        //检查结算账户
        if (settlementAccountId != null) accountService.checkAccount(settlementAccountId);
        if (salespersonId != null)  userService.checkUser(salespersonId);
        if (supplierId != null) supplierService.checkSupplier(supplierId);
        if (customerId != null) customerService.checkCustomer(customerId);
    }


    public <K, V> LinkedHashMap<K, V> reverseMap(Map<K, V> map) {
        // 将 Map 的条目转换为 List
        List<Map.Entry<K, V>> entries = new ArrayList<>(map.entrySet());

        // 倒转 List 中的顺序
        Collections.reverse(entries);

        // 创建一个新的 LinkedHashMap 来存储倒转后的顺序
        return entries.stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, // 处理键冲突的情况
                        LinkedHashMap::new
                ));
    }


}
